<template>
  <div class="bone-padding-10">
        <el-row style="margin-top:10px; margin-bottom: 20px;">
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item>设备管理</el-breadcrumb-item>
                <el-breadcrumb-item>中继信息</el-breadcrumb-item>
            </el-breadcrumb>
        </el-row>
        <el-row>
            <el-alert title="使用原生的 websocket" type="success"  :closable="false">
            </el-alert>
        </el-row>
        <el-row class="bone-top-10" :gutter='10'>
            <el-col :span='8'>
                <el-row :gutter='10'>
                    <el-col :span='18'>
                        <el-input size='small' v-model='base.sendMsg.content'></el-input>
                    </el-col>
                    <el-col :span='6'>
                        <el-button size='small' @click='send'>发送</el-button>
                    </el-col>
                </el-row>
            </el-col>
            <el-col :span='8'>{{base.receiveMsg}}</el-col>
        </el-row>
  </div>
</template>
<script>
let ws
export default {

  data(){
      return {
          base: {
              deptIdList : [],
              sendMsg:{
                  head: {
                      memberId: 0,
                      deptId: 0,
                      method: ''
                  },
                  content: ''
              },
              receiveMsg: ''
          }
      }
  },
  methods:{
        //初始化
      init(){
        let userInfo = JSON.parse(localStorage.getItem('userInfo'))
        console.log(userInfo)
        this.base.deptIdList = userInfo.myDeptIdList
        this.base.sendMsg.head.memberId = userInfo.memberId
        this.base.sendMsg.head.deptId = userInfo.deptId
      },

      websocketInit(){

          let _self = this
          if ("WebSocket" in window){
            ws = new WebSocket("ws://172.16.15.232:10000/myAlarm");
            ws.onopen = function(){
                _self.base.sendMsg.content = '用户连接'
                ws.send(JSON.stringify(_self.base.sendMsg))
                console.log('websocket连接成功')
            }

            ws.onmessage = function(evt){
                _self.onMessage(evt.data)
            }

            ws.onclose = function(){
                console.log("关闭ws")
            }


          }else{
              alert('您的浏览器不支持websocket')
          }
      },
      //收到websocket消息
      onMessage(msg){
        console.log(msg)
        this.base.receiveMsg = msg
      },

      send(){
          ws.send(JSON.stringify(this.base.sendMsg))
      }
  },
  mounted(){
      this.init()
      this.websocketInit()
  },
  destroyed(){
      console.log('vue 销毁')
      ws.close()
  }
}
</script>
<style scoped>

</style>
